﻿using System;
using System.Collections.Generic;
using Smart.Common;

namespace Smart.Util
{
	public abstract class CommandBase
	{
		public string Command { get; set; }
		public CommandBase Parent { get; set; }

		public string[] Args { get; set; }
		public int Index { get; set; }

		public Dictionary<string, CommandBase> SubCommands { get; set; }

		protected CommandBase(string command, CommandBase parent, string[] args, int index)
		{
			Command = command;
			Parent = parent;
			Args = args;
			Index = index;

			SubCommands = new Dictionary<string, CommandBase>(StringComparer.OrdinalIgnoreCase);
		}

		protected abstract void RegisterSubCommands();

		public virtual string GetFullCommand()
		{
			return
				Parent != null
					? Parent.GetFullCommand() + " " + Command
					: "Smart.Util " + Command;
		}

		public virtual bool Execute()
		{
			if (SubCommands.Count <= 0)
				return ExecuteInternal();

			var cmd = Args[Index];

			if (!cmd.IsNullOrEmpty())
			{
				var subCommand = SubCommands.SafeGet(cmd.TrimStart('/', '-'));

				if (subCommand != null)
				{
					return
						subCommand.Execute();
				}
			}

			var usagePrefix = GetFullCommand();

			Console.WriteLine("USAGE:");

			foreach (var kvp in SubCommands)
				Console.WriteLine(usagePrefix + " " + kvp.Value.Command);

			return false;
		}

		protected virtual bool ExecuteInternal()
		{
			return false;
		}

		protected virtual bool CheckArguments(int count, string arguments)
		{
			if (Args.Length > Index + count - 1)
				return true;

			Console.WriteLine("USAGE:");
			Console.WriteLine(string.Concat(GetFullCommand(), " ", arguments));

			return false;
		}
	}
}